package com.netease.xone.fragment;

import java.lang.reflect.Field;

import protocol.XoneCallBack;
import protocol.XoneService;
import protocol.meta.LoopBack;
import Utils.StackTraceUtil;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.actionbarsherlock.app.ActionBar;
import com.netease.log.NTLog;
import com.netease.pkgRelated.XoneConsts;
import com.netease.xone.adapter.AdapterBaseFragmentPager;
import com.netease.xone.view.MainContainerView;
import com.netease.xone.widget.tabview.MainTab;
import com.netease.xone.widget.tabview.MainTab.Param;

public class FragmentMain extends FragmentBase implements IFragmentMain{
    private String TAG = FragmentMain.class.getSimpleName();

    /**
     * 加载数据标志
     */
    private boolean bLoadData = false;
    /**
     * 加载菜单标志
     */
    private boolean bLoadActionBar = false;
    /**
     * 底部导航选中位置
     */
    private int mTabSelectedIndex = 0;
    private int mOffset = -1;
    private int mUnReadDuration = 2 * 60 * 1000;
    private MainContainerView mRootView;

    public static FragmentMain newInstance(Parcelable obj) {
        FragmentMain f = new FragmentMain();
        Bundle b = new Bundle();
        b.putParcelable("obj", obj);
        f.setArguments(b);
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        NTLog.d(TAG, StackTraceUtil.getMethodName() +
                " savedInstanceState=" + (null == savedInstanceState ? "null" : savedInstanceState.toString()));
        bLoadData = false;
        mRootView = new MainContainerView( getActivity(), this);

        if (null == savedInstanceState) {
            /**
             * 正常加载
             */
            loadData(null);
        } else {
            mOffset = savedInstanceState.getInt("offset");
        }

        XoneService.getInstance().addListener(mXoneCallBack);
        // 启动读取未读消息接口
        mRootView.postDelayed(mRunnable, mUnReadDuration);
        return mRootView;
    }

    @Override
    public void onRestoreCustomNonConfigurationInstance(Object obj) {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        /**
         * 换屏加载
         */
        loadData(obj);
    }

    @Override
    public void onResume() {
        NTLog.d(TAG, StackTraceUtil.getMethodName() + " bLoadData=" + bLoadData + " mOffset=" + mOffset);
        super.onResume();
        if (!bLoadData) {
            /**
             * 恢复加载
             */
            loadData(null);
            if (-1 != mOffset) {
                mRootView.getViewPager().setCurrentItem(mOffset);
            }
        }
    }

    private void loadData(Object obj) {
        NTLog.d(TAG, StackTraceUtil.getMethodName()
                + " obj=" + (null == obj ?  "null": obj.toString()));
        
        bLoadData = true;
        FragmentPagerAdapter adapter = null;
        if (obj != null) {
            /**
             * 由于重建Activity后getChildFragmentManager()会改变，所以要改变原有
             * FragmentPagerAdapter中的mFragmentManager变量
             */
            adapter = (FragmentPagerAdapter)obj;
            try {
                Field field = FragmentPagerAdapter.class.getDeclaredField("mFragmentManager");
                field.setAccessible(true);
                field.set(adapter, getChildFragmentManager());
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        mRootView.onInitPagerAndBottom(obj);
    }

    @Override
    public Object onRetainCustomNonConfigurationInstance() {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        if (null != mRootView) {
            return mRootView.getViewPager().getAdapter();
        }
        return null;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        super.onSaveInstanceState(outState);
        outState.putInt("offset", mRootView.getViewPager().getCurrentItem());
    }

    @Override
    public void onDestroy() {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        XoneService.getInstance().removeListener(mXoneCallBack);
        super.onDestroy();
        if (null != mRootView) {
            mRootView.removeCallbacks(mRunnable);
            mRootView.clear();
        }
        mRootView = null;
        mRunnable = null;
    }

    @Override
    public void onPageSelected(final int index) {
        NTLog.d(TAG, StackTraceUtil.getMethodName() + " index=" + index);
        ActionBar actionBar = getSherlockActivity().getSupportActionBar();
        mTabSelectedIndex = index;
        switch (mTabSelectedIndex) {
            case 0:
                if (bLoadActionBar) {
                    SubFragmentOnPageSeleted(index);
                } else {
                    mRootView.postDelayed(new Runnable() {
                        
                        @Override
                        public void run() {
                            SubFragmentOnPageSeleted(index);
                            bLoadActionBar = true;
                        }
                    }, 100);
                }
                break;
            case 1:
            case 2:
            case 3:
            case 4:
                actionBar.setDisplayShowCustomEnabled(false);
                actionBar.setDisplayShowTitleEnabled(true);
                SubFragmentOnPageSeleted(index);
                break;
            default:
                break;
        }
    }
    
    @Override
    public void onPageReSelected(int index) {
        SubFragmentOnPageReSeleted(index);
    }
    
    private void SubFragmentOnPageSeleted(int index) {
        Fragment fragment = getSherlockActivity().getSupportFragmentManager()
                .findFragmentByTag(AdapterBaseFragmentPager.makeFragmentName(mRootView.getViewPager().getId(), index));
        if (fragment instanceof IFragmentMain) {
            ((IFragmentMain)fragment).onPageSelected(index);
        }
    }
    
    private void SubFragmentOnPageReSeleted(int index) {
        Fragment fragment = getSherlockActivity().getSupportFragmentManager()
                .findFragmentByTag(AdapterBaseFragmentPager.makeFragmentName(mRootView.getViewPager().getId(), index));
        if (fragment instanceof IFragmentMain) {
            ((IFragmentMain)fragment).onPageReSelected(index);
        }
    }
    
    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            if (null != mRootView) {
                XoneService.getInstance().doGetUnReadInfoCount();
                mRootView.postDelayed(mRunnable, mUnReadDuration);
            }
        }
        
    };
    
    private XoneCallBack mXoneCallBack = new XoneCallBack() {

        @Override
        public void onLoopBack(int transactionId, Object obj) {
            if(obj != null && obj instanceof LoopBack){
                LoopBack lb = (LoopBack)obj;
                if(lb.mType == XoneConsts.LOOPBACK_TYPE.switch_account){
                    if(lb.mData != null && lb.mData instanceof Boolean){
                        boolean flag = (Boolean)lb.mData;
                        if (flag) {
                            if (0 != mRootView.getViewPager().getCurrentItem()) {
                                mRootView.getViewPager().setCurrentItem(0, false);
                            }
                        } else {
                            
                        }
                    }
                } else if (lb.mType == XoneConsts.LOOPBACK_TYPE.maintab_msg) {
                    if (null != mRootView && null != lb.mData && lb.mData instanceof Param) {
                        Param param = (Param)lb.mData;
                        MainTab mainTab = (MainTab)mRootView.getNav();
                        mainTab.setMsgVisibility(param.index, param.visibility);
                    }
                }
            }
        };
        
        @Override
        public void onGetUnReadInfoCount(int transactionId, Object obj) {
            int count = (Integer)obj;
            
            if (count > 0) {
                // 显示资讯有消息
                MainTab.showMsg(MainTab.INDEX_NEWS);
            }
        };
        
    };
    
}
